package com.jamaskii.dictation;

import androidx.constraintlayout.widget.ConstraintLayout;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.jamaskii.ecdict.WordBook;
import com.jamaskii.ecdict.WordBookStream;

import java.io.File;
import java.util.ArrayList;

public class HomeActivity extends BaseActivity {

    View layoutBooks;
    View layoutSettings;
    public ItemAdapter itemAdapter;
    public WordBookStream wordBookStream;
    public Handler hand=new Handler();
    public static HomeActivity instance;
    public long lastPressedTime=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        instance=this;
        init();
    }

    @Override
    public void onBackPressed(){
        if((System.currentTimeMillis()-lastPressedTime)<1500){
            this.finish();
        }else{
            Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
            lastPressedTime=System.currentTimeMillis();
        }
    }

    private void init(){
        try {
            setTopPadding();
            layoutBooks = LayoutInflater.from(this).inflate(R.layout.layout_books, null);
            layoutSettings = LayoutInflater.from(this).inflate(R.layout.layout_settings, null);
            setOnItemClick();

            loadBooks();
            linkData();

            //标题加粗
            TextView titleHome = findViewById(R.id.title_home);
            titleHome.getPaint().setFakeBoldText(true);

            turn(0);
        }catch (Exception e){
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        }
    }

    public void loadBooks(){
        wordBookStream=new WordBookStream(getExternalFilesDir(null).getAbsolutePath()+"/books/");
        wordBookStream.loadWordBooks();
    }

    private void freshMark(){
        ImageView imageGB=findViewById(R.id.image_mark_gb);
        ImageView imageUS=findViewById(R.id.image_mark_us);
        if(getDefaultPron()==1){
            imageGB.setVisibility(View.VISIBLE);
            imageUS.setVisibility(View.INVISIBLE);
        }else{
            imageGB.setVisibility(View.INVISIBLE);
            imageUS.setVisibility(View.VISIBLE);
        }
    }

    public void onPronClick(View view){
        switch (view.getId()){
            case R.id.label_gb:
                setDefaultPron(1);
                freshMark();
                break;
            case R.id.label_us:
                setDefaultPron(0);
                freshMark();
                break;
        }
    }

    public int getDefaultPron(){
        File file=new File(getExternalFilesDir(null).getAbsolutePath()+"/gb");
        if(file.exists()){
            return 1;
        }else{
            return 0;
        }
    }

    public boolean setDefaultPron(int dPron){
        File file=new File(getExternalFilesDir(null).getAbsolutePath()+"/gb");
        try{
            if(dPron==1){
                if (!file.exists()) {
                    file.createNewFile();
                }
            }else{
                if(file.exists()){
                    file.delete();
                }
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public void linkData(){
        ArrayList<ItemData> itemDatas=new ArrayList<>();
        for (WordBook book:wordBookStream.wordBooks
        ) {
            itemDatas.add(new ItemData(book,ItemType.SHOW_BOOK));
        }
        ItemData addBook=new ItemData(ItemType.ADD_BOOK);
        itemDatas.add(addBook);
        itemAdapter=new ItemAdapter(this,R.layout.item_book_show,itemDatas);

        ListView listBooks=layoutBooks.findViewById(R.id.list_book_home);
        listBooks.setDivider(getDrawable(R.color.lineGray));
        listBooks.setDividerHeight(1);
        listBooks.setAdapter(itemAdapter);
    }

    private void turn(int page){
        ImageView imageBook=findViewById(R.id.image_book_item_home);
        ImageView imageSettings=findViewById(R.id.image_settings);
        ImageView imageMultiSelect=findViewById(R.id.image_muilt_select);
        TextView labelBook=findViewById(R.id.label_books);
        TextView labelSettings=findViewById(R.id.label_setting);
        TextView titleHome=findViewById(R.id.title_home);
        ConstraintLayout containerHome=findViewById(R.id.layout_home_container);

        switch (page){
            case 0:
                imageBook.setImageDrawable(getDrawable(R.drawable.book_actived));
                imageSettings.setImageDrawable(getDrawable(R.drawable.settings_default));
                labelBook.setTextColor(getResources().getColor(R.color.themeColor));
                labelSettings.setTextColor(getResources().getColor(R.color.defaultGray));
                titleHome.setText("单词本");
                imageMultiSelect.setVisibility(View.VISIBLE);

                if(containerHome.getViewById(layoutSettings.getId())!=null){
                    containerHome.removeView(layoutSettings);
                }
                if(containerHome.getViewById(layoutBooks.getId())==null){
                    ConstraintLayout.LayoutParams layoutParams=new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT,ConstraintLayout.LayoutParams.MATCH_PARENT);
                    containerHome.addView(layoutBooks,layoutParams);
                }
                break;
            case 1:
                imageBook.setImageDrawable(getDrawable(R.drawable.book_default));
                imageSettings.setImageDrawable(getDrawable(R.drawable.settings_actived));
                labelBook.setTextColor(getResources().getColor(R.color.defaultGray));
                labelSettings.setTextColor(getResources().getColor(R.color.themeColor));
                titleHome.setText("设置");
                imageMultiSelect.setVisibility(View.INVISIBLE);

                if(containerHome.getViewById(layoutBooks.getId())!=null){
                    containerHome.removeView(layoutBooks);
                }
                if(containerHome.getViewById(layoutSettings.getId())==null){
                    ConstraintLayout.LayoutParams layoutParams=new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT,ConstraintLayout.LayoutParams.MATCH_PARENT);
                    containerHome.addView(layoutSettings,layoutParams);
                }
                freshMark();
                break;
        }
    }

    public void imageOnClick(View v){
        switch(v.getId()){
            case R.id.layoutBooks:
                turn(0);
                break;
            case R.id.image_book_item_home:
                turn(0);
                break;
            case R.id.layoutSettings:
                turn(1);
                break;
            case R.id.image_settings:
                turn(1);
                break;
        }
    }

    public void showMessage(String text){
        final String msg=text;
        this.hand.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(HomeActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onManagerClick(View v){
        Intent intent=new Intent();
        intent.setClass(HomeActivity.this,ManagerActivity.class);
        startActivity(intent);
    }

    private void setOnItemClick(){
        ListView listBooks=layoutBooks.findViewById(R.id.list_book_home);
        listBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int i, long l) {
                if(i==wordBookStream.wordBooks.size()){
                    showAddBookDialog();
                }else{
                    Intent intent=new Intent();
                    intent.setClass(HomeActivity.this,BookActivity.class);
                    intent.putExtra("index",i);
                    startActivity(intent);
                }
            }
        });

    }

    private void showAddBookDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(HomeActivity.this);
        final View layoutAddBook=getLayoutInflater().inflate(R.layout.dialog_input,null);
        builder.setTitle("新单词本名称");
        builder.setView(layoutAddBook);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                EditText editText=layoutAddBook.findViewById(R.id.textbox_content_input_dialog);
                WordBook wordBook=new WordBook();
                wordBook.name=editText.getText().toString();
                if(!wordBookStream.addBook(wordBook)){
                    if(wordBookStream.error.equals("WordBookAlreadyExitsException")){
                        showMessage("添加出错:单词本名称重复");
                    }
                    else{
                        showMessage("添加出错:未知错误");
                    }
                }
                loadBooks();
                linkData();
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(HomeActivity.this.getResources().getColor(R.color.themeColor));
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(HomeActivity.this.getResources().getColor(R.color.themeColor));
    }

    public void onAboutClick(View view){
        switch (view.getId()){
            case R.id.label_about:
                Intent intentAbout=new Intent();
                intentAbout.setClass(HomeActivity.this,AboutActivity.class);
                startActivity(intentAbout);
                break;
            case R.id.label_open_source:
                Intent intentOpenSource=new Intent();
                intentOpenSource.setData(Uri.parse(getString(R.string.git_link)));
                startActivity(intentOpenSource);
                break;
        }
    }

    public int getStatueBarHeight(){
        int statusBarHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight = getResources().getDimensionPixelSize(height);
            return statusBarHeight;
        } catch (Exception e) {
            return 24;
        }
    }

    private void setTopPadding(){
        ConstraintLayout layout=findViewById(R.id.padding_home) ;
        ViewGroup.LayoutParams layoutParams=layout.getLayoutParams();
        layoutParams.height=getStatueBarHeight();
        layout.setLayoutParams(layoutParams);
    }

}